// packageE/others/cloudwarehouse/cloudOrder/cloudOrder.js
import Toast from "../../../../dist/toast/toast";

// var WxParse = require('../../../wxParse/wxParse.js');

var app = getApp();
var location = require("../../../../mybehaviors/location/location");


Page({
  behaviors: [location],

  /**
   * 页面的初始数据
   */
  data: {
    clicktag: 0, // 方式提交订单多次点击
    language: "",
    //不同购买方式
    options: {}, //路由参数购买方式
    _root_tag: "",
    TAG_ACTION_BUY: "-2", //直接购买
    _goodsId: "",
    _optionsId: "",
    _total: 1,
    currentAddId: "",
    currentAddress: {},
    selectedMode: 0,
    selected: 0,
    dispatch: [],
    //优惠券标识
    popupSpecs: false,
    addressData: [],
    defaultAddress: {},
    realname: "", //收件人
    mobile: "",
    address: "",
    order_data: "",
    dispatch_price: 0,
    goods_price: 0,
    price: 0,
    discount_price: 0,
    deduction_price: 0,
    goodsInfo: {},
    //积分抵扣 其他抵扣
    checkDeductionList: [],
    //新增地址v2------------------------------------------------新增地址v2//
    form: {
      username: "",
      mobile: "",
      province: "",
      city: "",
      district: "",
      street: "",
      address: "",
      isDefault: false,
    },
    addressName: "",
    districtVal: "",
    popAddAddress: false,
    strShow: false, //街道显示
    openDateLw: false,
    provinceData: [],
    cityData: [],
    districtData: [],
    pickerValue: [0, 0, 0],
    selectAddressData: [],
    streetShow: false, //街道pop
    //新增地址v2------------------------------------------------新增地址v2//
    //留言
    note: {},
    submit_active: true,
    total_items: [],
    discount_amount_items: [],
    //服务费
    goodsId: "",

    point: {
      lat: "",
      lng: "",
    },
    city: "",
    defaultSelfCarry: {},
    orders_goods: {},

    integral: "",
    is_region: 0,
    TemplateArray: [],

    orderLocationObj: {
      positioning_success: 0,
      province: "",
      city: "",
    },
    getDispatch: false,
    is_selected: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    let userLocationFlag = await this.checkAlbum("scope.userLocation");
    console.log("userLocationFlag", userLocationFlag);
    if (!userLocationFlag) {
      return app.tips("获取位置失败，请重新进入后授权");
    }
    if (options.is_selected) {
      this.setData({
        selected: options.is_selected,
        is_selected: options.is_selected,
      });
    }
    try {
      const value = wx.getStorageSync("integral");
      if (value) {
        this.setData({
          integral: value,
        });
      }
    } catch (e) {
      // Do something when catch error
    }

    this.getCurrentOrderLocation();

    //不同购买方式
    this.setData({
      options: options,
      _root_tag: options.tag,
    });

    if (options.changeSelfCarry) {
      let changeSelfCarry = JSON.parse(options.changeSelfCarry);
      this.setData({
        defaultSelfCarry: changeSelfCarry,
      });
    }

    if (this.data._root_tag == this.data.TAG_ACTION_BUY) {
      this.setData({
        _goodsId: options.goodsId,
        _optionsId: options.optionsId,
        _total: options.total,
      });
      this._getDataActionBuy(); //直接购买
    }
    //加载地址数据初始化
    this._initAddressInfo();

    //如果Storage里有保存自提点的信息则自动获取填写
    let _zdtInfo = wx.getStorageSync("selfCarryInfo");
    if (_zdtInfo) {
      _zdtInfo = JSON.parse(_zdtInfo);
      this.setData({
        "linkinfo.name": _zdtInfo.distributionUserName || "",
        "linkinfo.mobile": _zdtInfo.distributionUserMobile || "",
      });
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let language = wx.getStorageSync("langIndex");
    this.setData({
      language: language.en,
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.data.submit_active = true;
  },
  goLocation_ro(e) {
    let form = this.data.form;
    let tag = this.data._root_tag;
    let store_id = this.data.store_id;
    let create = this.data.create;
    wx.navigateTo({
      url: "/packageC/o2o/o2oLocation_loc/o2oLocation_loc?tag=" +
        tag +
        "&store_id=" +
        store_id +
        "&form=" +
        JSON.stringify(form) +
        "&create=" +
        create,
    });
  },
  gotochangeSelfCarry() {
    //更换自提点
    let that = this;
    //保存自提点信息到本地，任务编号: 35632
    let _memberInfoes = {
      distributionUserName: this.data.linkinfo.name ?
        this.data.linkinfo.name :
        "",
      distributionUserMobile: this.data.linkinfo.mobile ?
        this.data.linkinfo.mobile :
        "",
    };
    try {
      wx.setStorageSync("selfCarryInfo", JSON.stringify(_memberInfoes));
    } catch (e) {
      console.log(e);
    }

    wx.navigateTo({
      url: "/packageC/selfCarry/selfCarry_info/selfCarry_info?tag=" +
        that.data.options.tag +
        "&goodsId=" +
        that.data.options.goodsId +
        "&optionsId=" +
        that.data.options.optionsId +
        "&total=" +
        that.data.options.total +
        "&iscloud=cloud" +
        "&goods=" +
        JSON.stringify(this._assembleGoods()),
    });
  },

  setDispatch(e) {
    let title = e.detail.title;
    this.data.dispatch.forEach((items) => {
      if (items.name == title) {
        this.setData({
          selected: items.dispatch_type_id,
          selectedMode: items.dispatch_type_id == "1" ? 0 : 1,
        });
      }
    });
    // console.log(this.data.selected)
    this._requestByAddress();
  },
  //显示地址pop
  showAddress() {
    //获取收货地址
    this._getAddress();
  },
  //获取收货地址
  _getAddress() {
    this.addressData = [];
    let that = this;
    let urlStr = app.getNetAddresss("member.member-address.index");
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          let defaultAddress = res.data;
          defaultAddress = res.data.filter(function (item) {
            return item.isdefault === 1;
          });

          that.setData({
            popupSpecs: true,
            addressData: res.data,
            defaultAddress: defaultAddress,
          });
        } else {
          Toast(res.msg);
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  //设置地址界面
  _setAddressViewData(model) {
    if (model == undefined || model == "" || model == []) {
      return;
    }
    //设置地址id
    this.data.currentAddId = model.id;
    this.data.currentAddress = model;
    this.setData({
      realname: app._isTextEmpty(model.username) ? "" : model.username,
      mobile: app._isTextEmpty(model.mobile) ? "" : model.mobile,
      address: app._isTextEmpty(model.province) ?
        "" :
        model.province +
        " " +
        model.city +
        " " +
        model.district +
        " " +
        (app._isTextEmpty(model.street) ? "" : model.street + " ") +
        model.address,
    });
  },
  isOrderAddress_M(_data) {
    //判断是否有订单需要填写地址，有一单需要填写地址则需要填写地址才可以下单
    //return false 提交订单需要填写地址
    for (let j = 0; j < _data.length; j++) {
      if (!_data[j].need_address) {
        console.log("有订单需要填写地址");
        return false;
      }
    }
    return true;
  },
  //设置界面
  _setViewData(data) {
    console.log("走了_setViewData设置界面方法");
    let _show_address = this.isOrderAddress_M(data.orders);

    this.setData({
      dispatch: [{
        name: "快递",
        dispatch_type_id: "1"
      },
      {
        name: "上门自提",
        dispatch_type_id: "8"
      }
      ],
      selected: this.data.selected,
      selectedMode: this.data.selected == "1" ? 0 : 1,
      order_data: data.orders,
      show_address: _show_address,
      price: data.total_price, //设置总价格（合计）
      total_items: data.amount_items,
      discount_amount_items: data.discount_amount_items,
      none_loc: true,
      clicktag: 0,
    });

    this.data.dispatch.forEach((items) => {
      if (items.dispatch_type_id == 8) {
        console.log("有自提点配送方式，请求定位获取自提点列表");
        this._getLocation(() => {this.getList();});
      }
    });
  },
  //提货人输入
  infonamebtn(e) {
    let infoname = e.detail;
    this.setData({
      "linkinfo.name": infoname,
    });
  },
  infonameclear() {
    this.setData({
      "linkinfo.name": "",
    });
  },
  infomobileclear() {
    this.setData({
      "linkinfo.mobile": "",
    });
  },
  //提货人手机输入
  infomobilebtn(e) {
    let infomobile = e.detail;
    this.setData({
      "linkinfo.mobile": infomobile,
    });
  },
  addresclosebtn: function () {
    this.setData({
      popupSpecs: false,
    });
  },
  //选择地址
  selectAddress(e) {
    let item = e.currentTarget.dataset.addr;
    this._setAddressViewData(item); //更新界面 & ID
    this._requestByAddress(); //选择地址后重新计算
    //关闭 地址栏
    this.setData({
      popupSpecs: false,
    });
  },
  //选择地址后重新计算数据
  _requestByAddress() {
    //重新计算
    this.setData({
      order_data: "",
    });
    this._getDataActionBuy(); //直接购买
  },
  editAddress(e) {
    let loc = e.currentTarget.dataset.item;
    this.setData({
      "form.address_id": this.data.defaultAddress[0].id,
      "form.username": this.data.defaultAddress[0].username,
      "form.mobile": this.data.defaultAddress[0].mobile,
      "form.province": this.data.defaultAddress[0].province,
      "form.city": this.data.defaultAddress[0].city,
      "form.district": this.data.defaultAddress[0].district,
      "form.address": this.data.defaultAddress[0].address,
      "form.street": this.data.defaultAddress[0].street,
      "form.isDefault": this.data.defaultAddress[0].isDefault === 0 ? false : true,
      "is_point.lng": loc.longitude,
      "is_point.lat": loc.latitude,
    });
    this.setData({
      popupSpecs: false,
      create: false,
      popAddAddress: true,
    });
    this._getStreet(this.data.defaultAddress[0].district_id);
    this.setData({
      addressName: this.data.form.province +
        " " +
        this.data.form.city +
        " " +
        this.data.form.district,
    });
  },
  //关闭增加地址
  popAddressClose() {
    this.setData({
      popAddAddress: false,
    });
  },
  //收件人输入绑定
  usernameinp: function (e) {
    let nameval = e.detail.value;
    this.setData({
      "form.username": nameval,
    });
  },
  //联系电话输入绑定
  mobileinp: function (e) {
    let mobileval = e.detail.value;
    this.setData({
      "form.mobile": mobileval,
    });
  },
  //默认地址开关值绑定
  isDefaultChange: function (e) {
    let isDefault = e.detail;
    this.setData({
      "form.isDefault": isDefault,
    });
  },
  //详细地址绑定输入
  addressinp: function (e) {
    let addressval = e.detail.value;
    this.setData({
      "form.address": addressval,
    });
  },
  // 关闭选择收货地址
  _closeDateLw: function () {
    this.setData({
      openDateLw: false,
    });
  },
  //地址选择器数据初始化
  _initAddressInfo: function () {
    var that = this;
    var _keyName = "provinceData";
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        console.log("地址信息准备就绪");
        that._getProvinceData();
      },
      fail: function (res) {
        console.log("省fail");
        app._getNetWork({
          url: app.getNetAddresss("member.member-address.address"),
          success: function (res) {
            var response = res.data;
            var province = response.data.province;
            var city = response.data.city;
            var district = response.data.district;
            wx.setStorage({
              key: "provinceData",
              data: province,
            });
            wx.setStorage({
              key: "cityData",
              data: city,
            });
            wx.setStorage({
              key: "districtData",
              data: district,
            });
            that._initAddressInfo();
          },
          fail: function (res) {},
          state: true,
        });
      },
    });
  },
  // 读取省key
  _getProvinceData: function () {
    var that = this;
    var _keyName = "provinceData";
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        // console.log("省读取成功", res.data);
        that.setData({
          provinceData: res.data,
        });
        that.setData({
          "selectAddressData[0].name": res.data[that.data.pickerValue[0]].areaname,
          "selectAddressData[0].id": res.data[that.data.pickerValue[0]].id,
          "selectAddressData[0].index": that.data.pickerValue[0],
        });
        that._getCityData();
      },
    });
  },
  // 读取城市key，筛选城市data
  _getCityData: function () {
    var _data = this.data.selectAddressData[0];
    // console.log("城市", "_data", _data);
    var that = this;
    var _keyName = "cityData";
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        // console.log("城市读取成功", res);

        var _json = [];
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].parentid == _data.id) {
            _json.push(res.data[i]);
          }
        }
        // console.log("城市数据筛选", _json);
        that.setData({
          cityData: _json,
        });
        that.setData({
          "selectAddressData[1].name": _json[that.data.pickerValue[1]].areaname,
          "selectAddressData[1].id": _json[that.data.pickerValue[1]].id,
          "selectAddressData[1].index": that.data.pickerValue[1],
        });
        that._getDistrictData();
      },
    });
  },
  // 读取地区key，筛选地区data
  _getDistrictData: function () {
    var _data = this.data.selectAddressData[1];
    // console.log("地区", "_data", _data)
    var that = this;
    var _keyName = "districtData";
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        console.log("地区读取成功");
        var _json = [];
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].parentid == _data.id) {
            _json.push(res.data[i]);
          }
        }
        // console.log("地区数据筛选", _json);
        that.setData({
          districtData: _json,
        });
        // console.log("districtData", _json);
        that.setData({
          "selectAddressData[2].name": _json[that.data.pickerValue[2]].areaname,
          "selectAddressData[2].id": _json[that.data.pickerValue[2]].id,
          "selectAddressData[2].index": that.data.pickerValue[2],
        });
        // console.log("over", that.data.selectAddressData);
      },
    });
  },
  //打开地址选择器
  openDateLwtbtn: function () {
    this.setData({
      openDateLw: true,
    });
  },
  // 收货地址滚动事件
  bindChange: function (e) {
    var val = e.detail.value;
    if (this.data.pickerValue[0] != val[0]) {
      val[1] = 0;
      val[2] = 0;
    }
    if (this.data.pickerValue[1] != val[1]) {
      val[2] = 0;
    }
    this.setData({
      "pickerValue[0]": val[0],
      "pickerValue[1]": val[1],
      "pickerValue[2]": val[2],
    });
    this._initAddressInfo();
  },
  // 确定选择收货地址
  _okAddress: function () {
    let seleData = this.data.selectAddressData;
    this.setData({
      "form.street": "",
      districtVal: "",
      addressName: seleData[0].name + " " + seleData[1].name + " " + seleData[2].name,
      "form.province": seleData[0].name,
      "form.city": seleData[1].name,
      "form.district": seleData[2].name,
    });
    this._getStreet(seleData[2].id);
    this._closeDateLw();
  },
  //获取街道
  _getStreet(param) {
    let that = this;
    let urlStr = app.getNetAddresss("member.memberAddress.street");
    urlStr += "&district_id=" + param;
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1 && !app._isTextEmpty(res.data)) {
          if (!app._isTextEmpty(res.data) && res.data.length > 0) {
            that.setData({
              districtVal: res.data,
              strShow: true,
            });
          } else {
            that.setData({
              strShow: false,
            });
          }
        } else {
          that.setData({
            strShow: false,
          });
        }
      },
      fail: function (res) {
        that.setData({
          strShow: false,
        });
        console.log(res);
      },
    });
  },
  streetChoose() {
    if (this.data.is_region == 1 && app._isTextEmpty(this.data.addressName)) {
      wx.showToast({
        icon: "none",
        title: "请先选择所在地区",
        duration: 1500,
      });
    } else {
      this.setData({
        streetShow: true,
      });
    }
  },
  //关闭选择街道弹窗
  streetClose: function () {
    this.setData({
      streetShow: false,
    });
  },
  //选择街道
  streetConfirm(e) {
    let strname = e.target.dataset.strname;
    this.setData({
      "form.street": strname,
      streetShow: false,
    });
  },
  //增加地址
  appendAddress(e) {
    let that = this;
    let apptype = e.currentTarget.dataset.apptype;
    if (app._isTextEmpty(this.data.form.username)) {
      wx.showToast({
        icon: "none",
        title: "请输入收货人姓名",
        duration: 1500,
      });
      return;
    }
    if (app._isTextEmpty(this.data.form.mobile)) {
      wx.showToast({
        icon: "none",
        title: "请输入联系电话",
        duration: 1500,
      });
      return;
    }
    if (!/^[0-9]{1,}$/.test(this.data.form.mobile)) {
      wx.showToast({
        icon: "none",
        title: "请输入联系电话",
        duration: 1500,
      });
      return;
    }
    if (this.data.is_region == 1 && app._isTextEmpty(this.data.addressName)) {
      wx.showToast({
        icon: "none",
        title: "请选择所在区域",
        duration: 1500,
      });
      return;
    }
    if (
      this.data.is_region == 1 &&
      this.data.strShow &&
      app._isTextEmpty(this.data.form.street)
    ) {
      wx.showToast({
        icon: "none",
        title: "请选择所在街道",
        duration: 1500,
      });
      return;
    }
    if (app._isTextEmpty(this.data.form.address)) {
      wx.showToast({
        icon: "none",
        title: "请输入详细地址",
        duration: 1500,
      });
      return;
    }
    let json = {
      username: this.data.form.username,
      mobile: this.data.form.mobile,
      province: this.data.form.province,
      city: this.data.form.city,
      district: this.data.form.district,
      address: this.data.form.address,
      isdefault: this.data.form.isDefault ? 1 : 0,
      address_id: this.data.form.address_id,
    };
    if (this.data.is_point) {
      json.longitude = this.data.is_point.lng;
      json.latitude = this.data.is_point.lat;
    }
    if (this.data.strShow) {
      json.street = this.data.form.street;
    }
    let urlStr = "";
    if (apptype === "update") {
      urlStr = app.getNetAddresss("member.member-address.update");
    } else {
      urlStr = app.getNetAddresss("member.member-address.store");
    }
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: json,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          Toast(res.msg);
          that.popAddressClose();
          that._setAddressViewData(res.data);
          that._requestByAddress(); //选择地址后重新计算
          that.setData({
            "form.username": "",
            "form.mobile": "",
            "form.province": "",
            "form.city": "",
            "form.district": "",
            "form.street": "",
            "form.address": "",
            "form.isDefault": false,
            addressName: "",
          });
        } else {
          Toast(res.msg);
        }
      },
      fail: function (res) {},
    });
  },
  //跳转到新增地址
  addAddress() {
    this.getIsOpenAddress();
    //关闭 地址栏
    this.setData({
      popupSpecs: false,
    });
    //新增地址 本地处理
    console.log(this.data.delivery_status, this.data.selected);
    this.showAddAddress();
  },
  getIsOpenAddress() {
    var that = this;
    let urlStr = app.getNetAddresss("member.member-address.is-region");
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1 && !app._isTextEmpty(res.data)) {
          that.setData({
            is_region: res.data.is_region,
          });
        } else {
          console.log(res.msg);
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  //显示增加地址
  showAddAddress() {
    this.setData({
      "form.username": "",
      "form.mobile": "",
      "form.province": "",
      "form.city": "",
      "form.district": "",
      "form.street": "",
      "form.address": "",
      "form.isDefault": false,
      addressName: "",
      popAddAddress: true,
      create: true,
    });
  },
  // 留言
  noteHandle(e) {
    let preid = e.target.dataset.preid;
    let item = e.target.dataset.item;
    let val = e.detail.value;
    this.setData({
      ["note." + preid]: val,
    });
    // 触发抵扣事件
    if (!item.order_deductions[0]) {
      //临时数据
      let isHasNote = false;
      if (this.data.checkDeductionList.length > 0) {
        this.data.checkDeductionList = this.data.checkDeductionList.map((deduction, index) => {
          if (deduction.pre_id == item.pre_id) {
            isHasNote = true;
            deduction.note = this.data.note[item.pre_id];
          }
        });
      }
      if (!isHasNote) {
        this.data.checkDeductionList.push({
          deduction_ids: [],
          pre_id: item.pre_id,
          note: this.data.note[item.pre_id]
        });
      }
      this.setData({
        checkDeductionList: this.data.checkDeductionList,
      });
    } else {
      this._screenDiscount(item, item.order_deductions[0]);
    }
  },
  //筛选抵扣
  _screenDiscount(item, value) {
    //临时数据
    if (this.data.checkDeductionList.length > 0) {
      this.data.checkDeductionList = this.data.checkDeductionList.map((deduction, index) => {
        if (deduction.pre_id == item.pre_id) {
          if (value.checked) {
            // 选中的时候检查是否有对应的code
            if (deduction.deduction_ids && deduction.deduction_ids.indexOf(value.code) == -1) {
              deduction.deduction_ids.push(value.code);
            }
          } else {
            // 取消选中的时候检查去掉对应的code
            if (deduction.deduction_ids && deduction.deduction_ids.indexOf(value.code) > -1) {
              deduction.deduction_ids.splice(deduction.deduction_ids.indexOf(value.code), 1);
            }
          }

          // 留言和安装选项重新赋值
          deduction.note = this.data.note[item.pre_id];
          deduction.service_fee = this.data.service_fee[item.pre_id];
        }
      });
    } else {
      this.data.checkDeductionList.push({
        deduction_ids: [value.code],
        pre_id: item.pre_id,
        note: this.data.note[item.pre_id],
        service_fee: this.data.service_fee[item.pre_id]
      });
    }

    this.setData({
      checkDeductionList: this.data.checkDeductionList,
    });
  },
  //直接购买
  _getDataActionBuy() {
    let that = this;
    let urlStr = "";
    urlStr = app.getNetAddresss("plugin.cloud-warehouse.frontend.goods-buy.index");
    urlStr += "&goods_id=" + this.data._goodsId;
    urlStr += "&total=" + this.data._total;
    urlStr += "&option_id=" + this.data._optionsId;
    urlStr += "&member_coupon_ids=" + [];
    urlStr += "&orders=" + JSON.stringify([]);
    urlStr += "&address=" + encodeURIComponent(JSON.stringify(this.data.currentAddress));
    urlStr += "&dispatch_type_id=" + this.data.selected;
    //自提点开启
    if (this.data.selected == 8) {
      urlStr += "&package_deliver_id=" + this.data.defaultSelfCarry.id;
    }
    urlStr += "&mark=" + (this.data.options.mark ? this.data.options.mark : 0);
    if (this.data.clicktag == 0) {
      this.setData({
        clicktag: 1,
      });
      app._getNetWork({
        url: urlStr,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              goodsInfo: res.data,
              cup_notice: true,
            });
            that._setViewData(res.data); //设置界面
            that._setAddressViewData(res.data.dispatch.default_member_address); //设置地址界面
          } else {
            that.setData({
              cup_notice: true,
            });
            Toast(res.msg);
          }
          setTimeout(function () {
            that.setData({
              clicktag: 0,
            });
          }, 1000);
        },
        fail: function (res) {
          console.log(res);
        },
      });
    }
  },
  //获取模板id
  getTemplate() {
    let urlStr = app.getNetAddresss("member.member.getMiniTemplateCorrespond");
    let that = this;
    app._getNetWork({
      url: urlStr,
      data: {
        small_type: 1,
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          let array = [];
          for (let i = 0; i < res.data.length; i++) {
            array.push(res.data[i].template_id);
          }
          that.setData({
            TemplateArray: array,
          });
          wx.requestSubscribeMessage({
            tmplIds: that.data.TemplateArray,
            success(res) {
              console.log(res, "success");
              that.submitBtn();
            },
            fail(err) {
              console.log(err, "err");
              that.submitBtn();
            },
          });
        } else {
          Toast(res.msg);
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  //提交订单
  submit() {
    this.getTemplate();
  },
  submitBtn() {
    if (this.data.submit_active == true) {
      this.data.submit_active = false;
      if (this.data.selected == 8) {
        if (app._isTextEmpty(this.data.defaultSelfCarry.id)) {
          wx.showModal({
            title: "提示",
            content: "请选择自提点",
            showCancel: false,
            confirmText: "确定",
            confirmColor: "#000000",
            success: (res) => {},
            fail: function (res) {},
            complete: function (res) {},
          });
          this.data.submit_active = true;
          return;
        }
        if (app._isTextEmpty(this.data.linkinfo.name)) {
          wx.showModal({
            title: "提示",
            content: "请填写提货人姓名",
            showCancel: false,
            confirmText: "确定",
            confirmColor: "#000000",
            success: (res) => {},
          });
          this.data.submit_active = true;
          return;
        }
        if (app._isTextEmpty(this.data.linkinfo.mobile)) {
          wx.showModal({
            title: "提示",
            content: "请输入提货人手机",
            showCancel: false,
            confirmText: "确定",
            confirmColor: "#000000",
            success: (res) => {},
          });
          this.data.submit_active = true;
          return;
        }
        //保存自提点信息到本地，任务编号: 35632
        let _memberInfoes = {
          distributionUserName: this.data.linkinfo.name ?
            this.data.linkinfo.name :
            "",
          distributionUserMobile: this.data.linkinfo.mobile ?
            this.data.linkinfo.mobile :
            "",
        };
        try {
          wx.setStorageSync("selfCarryInfo", JSON.stringify(_memberInfoes));
        } catch (e) {
          console.log(e);
        }
      }
      if (
        !this.isOrderAddress_M(this.data.order_data) &&
        (this.data.selected == 1 || this.data.selected == 3)
      ) {
        if (app._isTextEmpty(this.data.currentAddId)) {
          wx.showModal({
            title: "提示",
            content: "请选择收货地址",
            showCancel: false,
            confirmText: "确定",
            confirmColor: "#000000",
            success: (res) => {
              this.showAddress();
            },
            fail: function (res) {},
          });
          this.data.submit_active = true;
          return;
        }
      }

      let that = this;
      let json = this._assembleJson();
      let urlStr;
      urlStr = app.getNetAddresss(
        "plugin.cloud-warehouse.frontend.create.index"
      );
      if (this.data.clicktag == 0) {
        this.setData({
          clicktag: 1,
        });
        app._postNetWork({
          url: urlStr,
          showToastIn: false,
          data: json,
          success: function (resdata) {
            var res = resdata.data;
            if (res.result == 1) {
              wx.showToast({
                title: "下单成功",
                icon: "none",
                duration: 1000,
                success: function () {
                  setTimeout(() => {
                    wx.navigateBack({
                      delta: 2,
                    });
                  }, 900);
                },
              });
            } else {
              Toast(res.msg);
            }
            setTimeout(function () {
              that.setData({
                clicktag: 0,
              });
            }, 1000);
          },
          fail: function (res) {
            console.log(res);
          },
        });
      }
    }
  },
  //组装商品信息
  _assembleGoods() {
    let newGoods = [];
    for (let j = 0; j < this.data.goodsInfo.orders.length; j++) {
      for (
        let i = 0; i < this.data.goodsInfo.orders[j].order_goods.length; i++
      ) {
        let model = {};
        model.goods_id = this.data.goodsInfo.orders[j].order_goods[i].goods_id;
        model.total = this.data.goodsInfo.orders[j].order_goods[i].total;
        model.option_id = this.data.goodsInfo.orders[j].order_goods[
          i
        ].goods_option_id;
        newGoods.push(model);
      }
    }
    return newGoods;
  },
  //组装json数据
  _assembleJson() {
    let json = {};
    if (this.data._root_tag == this.data.TAG_ACTION_BUY) {
      json = {
        dispatch_type_id: this.data.selected,
        address: encodeURIComponent(JSON.stringify(this.data.currentAddress)),
        goods: JSON.stringify(this._assembleGoods()),
        member_coupon_ids: JSON.stringify([]),
        orders: JSON.stringify([]),
        mark: this.data.options.mark ? this.data.options.mark : 0,
        invoice_type: this.data.iscur_c ? 0 : 1, // 发票
        rise_type: this.data.iscur ? 1 : 0,
        call: this.data.invoice_list.call,
        email: this.data.invoice_list.email,
        company_number: this.data.invoice_list.company_number,
      };
    }

    if (this.data.selected == 8) {
      json.dispatch_type_id = this.data.selected;
      json.package_deliver_id = this.data.defaultSelfCarry.id;
      json.realname = this.data.linkinfo.name;
      json.mobile = this.data.linkinfo.mobile;
      delete json.address;
    }
    Object.assign(json, this.data.orderLocationObj);
    return json;
  },


  getList() {
    let that = this;
    let urlStr = app.getNetAddresss(
      "plugin.package-deliver.frontend.deliver.getList"
    );
    let point = app.qqMapTransBMap(
      parseFloat(that.data.point.lng),
      parseFloat(that.data.point.lat)
    );
    app._getNetWork({
      url: urlStr,
      data: {
        city_name: that.data.city,
        lat: point.lat,
        lng: point.lng,
        kwd: "",
        goods: JSON.stringify(this._assembleGoods()),
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            defaultSelfCarry: JSON.stringify(that.data.defaultSelfCarry) == "{}" ?
              res.data.list.data[0] :
              that.data.defaultSelfCarry,
          });
        } else {
          wx.showToast({
            icon: "none",
            title: "获取自提点失败",
            duration: 1000,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  //获取经纬度
  getCurrentOrderLocation() {
    this._getLocation((mapdata, e) => {
      let orderLocationObj = {
        positioning_success: 1,
        register_province: mapdata.address_component.province,
        register_city: this.data.city
      };
      this.data.orderLocationObj = orderLocationObj;
    });

  },

  checkAlbum(scopeName) {
    return new Promise(async (resolve, reject) => { // eslint-disable-line
      let writePhotosAlbum = await this.getAuthSetting(scopeName);
      if (!writePhotosAlbum) {
        wx.showModal({
          title: "请开启授权",
          content: "是否跳转设置页开启授权",
          success(res) {
            if (res.confirm) {
              wx.openSetting({
                success(settingdata) {
                  if (settingdata.authSetting[scopeName]) {
                    resolve(true);
                  } else {
                    resolve(false);
                  }
                },
              });
            } else if (res.cancel) {
              resolve(false);
            }
          },
          fail: () => {
            resolve(false);
          },
        });
      } else resolve(true);
    });
  },
  getAuthSetting(authName) {
    return new Promise((resolve, reject) => {
      wx.getSetting({
        success(res) {
          if (!res.authSetting[authName]) {
            wx.authorize({
              scope: authName,
              success() {
                resolve(true);
              },
              fail() {
                resolve(false);
              },
            });
          } else resolve(true);
        },
        fail() {
          resolve(false);
        },
      });
    });
  },
});